/*
 * @Author: your name
 * @Date: 2021-12-17 15:31:19
 * @LastEditTime: 2022-05-16 09:59:27
 * @LastEditors: 陈宇 975155172@qq.com
 * @Description: 接口方法 （增 删 改 查）
 * @FilePath: \blog-api\src\user\user.service.ts
 */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In, Like } from 'typeorm';
import { tagsDto, addTagsPostDto, removeTagsPostDto, QueryTagsDto } from './dto/create-post.dot';
import { Tags } from './entities/tags.entity';

@Injectable()
export class TagsService {
  // 使用InjectRepository装饰器并引入Repository这样就可以使用typeorm的操作了
  constructor(
    @InjectRepository(Tags)
    private readonly tagsRepository: Repository<Tags>,
  ) {}
  
  // 获取标签列表
  async list(body): Promise<tagsDto> {
    let tagsTotalList: any,
      tagsTotal: any,
      tagsList: any;
      
    if(!body.page) {
      [ tagsTotalList, tagsTotal ] = await this.tagsRepository.findAndCount()
    } else {
      [ tagsList, tagsTotal ] = await this.tagsRepository.findAndCount({
        take: body.page_count,
			  skip: (body.page - 1) * body.page_count,
        where: {
          id: body.id,
          tag_name: Like(`%${ body.name ? body.name : '' }%`)
        }
      })
    }
    return {
      list: tagsTotalList ? tagsTotalList : tagsList,
      total: Number(tagsTotal),
      page: body.page,
      pageCount: Math.ceil(Number(tagsTotal) / body.page_count),
      pageSize: body.page_count
    };
  }

  // 根据ID 获取标签
  async queryTags(body: QueryTagsDto): Promise<any> {
    const result = await this.tagsRepository.findBy({
      id: In(body.ids)
    })

    return result;
  }

  // 添加 / 修改 标签
  async addEditorTags(body: addTagsPostDto): Promise<{message: string}> {
    if(body.id) {
      await this.tagsRepository.update(body.id, {
        tag_name: body.name,
        describe: body.describe
      });
    }
    else {
      const tag = this.tagsRepository.create({
        tag_name: body.name,
        describe: body.describe
      });
      await this.tagsRepository.save(tag);
    }

    return {
      message: body.id ? '修改成功' : '添加成功'
    }
  }

  // 删除标签
  async removeTag(body: removeTagsPostDto): Promise<tagsDto> {
    await this.tagsRepository.delete(body.id);
    return {}
  }
}
